package xcmg.device.web.sale;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.sale.SaleIntentionDO;
import xcmg.device.dao.entity.warehouse.WarehouseDO;
import xcmg.device.infra.AuthCode;
import xcmg.device.infra.BasicController;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.JsonUtil;
import xcmg.device.infra.annotation.ExternalApiRequest;
import xcmg.device.infra.enums.SaleStatus;
import xcmg.device.infra.interceptor.externalApiCheck.handle.ApiCheckStrategy.ApiCheckOptionEnum;
import xcmg.device.service.ExternalParamCheckService;
import xcmg.device.service.crm.util.ActionResultUtil;
import xcmg.device.service.delivery.DeliveryNoteService;
import xcmg.device.service.sale.SaleIntentionService;
import xcmg.device.service.vo.FunctionResult;
import xcmg.device.service.vo.sale.DeleteReasonVO;
import xcmg.device.service.vo.sale.SaleAddVO;
import xcmg.device.service.vo.sale.SaleIntentionDetailVO;
import xcmg.device.service.vo.sale.SaleIntentionVO;
import xcmg.device.service.warehouse.allot.RegionAllotService;
import xcmg.device.util.DecimalUtil;
import xcmg.device.util.RedisConstant;
import yb.ecp.fast.feign.AuthClient;
import yb.ecp.fast.infra.annotation.FastMappingInfo;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;
import yb.ecp.fast.infra.infra.log.LogHelper;
import yb.ecp.fast.infra.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by GYJ on 2018-01-10.
 */
@Slf4j
@RequestMapping("/saleIntention")
@RestController
public class SaleIntentionController extends BasicController{

    @Autowired
    private SaleIntentionService saleIntentionService;
    @Autowired
    private RegionAllotService regionAllotService;

    @Autowired
    private ExternalParamCheckService externalParamCheckService;
    @Autowired
    private AuthClient authClient;
    @Autowired
    private RedissonClient redissonClient;

    private final static Object obj = new Object();

    @RequestMapping(value = "/list",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult list(@RequestBody SearchCommonVO<SaleIntentionVO> condition)throws Exception{
        if(condition==null){
            return actionResult(ErrorCode.IllegalArument);
        }
        if(condition.getFilters()==null){
            SaleIntentionVO filters=new SaleIntentionVO();
            filters.setSupplierOrgId(getOrgId());
            condition.setFilters(filters);
        }
        else {
            condition.getFilters().setSupplierOrgId(getOrgId());
        }
        PageCommonVO pageCommonVO=saleIntentionService.list(condition);
        return actionValueResult(pageCommonVO.getPageInfo());
    }
    
    @RequestMapping(value = "/listByUser",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult listByUser(@RequestBody SearchCommonVO<SaleIntentionVO> condition)throws Exception{
    	if(condition==null){
            return actionResult(ErrorCode.IllegalArument);
        }
        if(condition.getFilters()==null){
            SaleIntentionVO filters=new SaleIntentionVO();
            filters.setSupplierOrgId(getOrgId());
            condition.setFilters(filters);
        }
        else {
            condition.getFilters().setSupplierOrgId(getOrgId());
        }
        PageCommonVO pageCommonVO=saleIntentionService.listByUser(condition, getUserId());
        return actionValueResult(pageCommonVO.getPageInfo());
    }


    @RequestMapping(value = "/save",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult save(@RequestBody SaleAddVO model)throws Exception{
        if(model==null){
            return actionResult(ErrorCode.IllegalArument);
        }
        model.getHeaderInfo().setStatus(String.valueOf(SaleStatus.Saved.getCode()));
        model.getHeaderInfo().setCreatorId(getUserId());
        model.getHeaderInfo().setSupplierOrgId(getOrgId());
        model.getHeaderInfo().setCreateName(getUserName());
        ErrorCode ret=ErrorCode.Success;
        String lockKey = model.getHeaderInfo().getPurchaseNo();
        RLock lock = null;
        try{
            if(!StringUtils.isEmpty(model.getHeaderInfo().getSaleNo())){
                ret=saleIntentionService.update(model,getOrgId(),getUserId(),getUserName());
            }else {
                if(!StringUtils.isEmpty(lockKey)){//需要加锁
                    String saleIntentionSaveCacheKey = RedisConstant.RedisKeyContant.SALE_INTENTION_CREATE_LOCK_KEY+lockKey;
                    lock = redissonClient.getLock(saleIntentionSaveCacheKey);
                    boolean isLock;
                    try {
                        isLock = lock.tryLock(0,RedisConstant.SALE_INTENTION_CREATE_LOCK_OUTTIME, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                        log.error("保存销售订单获取分布式锁异常{}",e);
                        return actionResult(ErrorCode.SALE_INTENTION_CREATE_LOCK_ERROR);
                    }
                    if(!isLock){
                        log.warn("保存销售订单存在已经执行的任务,无法获取锁，本次不执行");
                        return actionResult(ErrorCode.SALE_INTENTION_CREATE_LOCK_ERROR);
                    }
                }
                //为每条记录详情生成行号
                generalLineNo4SaleIntentionDetail(model);
                //业务处理
                ret = saleIntentionService.add(model);
            }
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }finally {
            if(lock != null){
                lock.unlock();
            }
        }
        return actionResult(ret);
    }
    @RequestMapping(value = "/submit",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult submit(@RequestBody SaleAddVO model)throws Exception{
        if(model==null){
            return actionResult(ErrorCode.IllegalArument);
        }
        model.getHeaderInfo().setStatus(String.valueOf(SaleStatus.Submit.getCode()));
        model.getHeaderInfo().setCreatorId(getUserId());
        model.getHeaderInfo().setSupplierOrgId(getOrgId());
        model.getHeaderInfo().setCreateName(getUserName());
        model.getHeaderInfo().setCashShortAndOver(DecimalUtil.yuan2fenDefauleZero(model.getHeaderInfo().getCashShortAndOver()));
        ErrorCode ret=ErrorCode.Success;
        String lockKey = model.getHeaderInfo().getPurchaseNo();
        RLock lock = null;
        try{
            if(!StringUtils.isEmpty(model.getHeaderInfo().getSaleNo())){
                ret=saleIntentionService.update(model,getOrgId(),getUserId(),getUserName());
            }else {
                if(!StringUtils.isEmpty(lockKey)){//需要加锁
                    String saleIntentionSaveCacheKey = RedisConstant.RedisKeyContant.SALE_INTENTION_CREATE_LOCK_KEY+lockKey;
                    lock = redissonClient.getLock(saleIntentionSaveCacheKey);
                    boolean isLock;
                    try {
                        isLock = lock.tryLock(0,RedisConstant.SALE_INTENTION_CREATE_LOCK_OUTTIME, TimeUnit.SECONDS);
                    } catch (InterruptedException e) {
                        log.error("保存销售订单获取分布式锁异常{}",e);
                        return actionResult(ErrorCode.SALE_INTENTION_CREATE_LOCK_ERROR);
                    }
                    if(!isLock){
                        log.warn("保存销售订单存在已经执行的任务,无法获取锁，本次不执行");
                        return actionResult(ErrorCode.SALE_INTENTION_CREATE_LOCK_ERROR);
                    }
                }
                //为每一条零件详情生成pms的行号
                generalLineNo4SaleIntentionDetail(model);
                //业务处理
                ret = saleIntentionService.add(model);
            }
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }finally {
            if(lock != null){
                lock.unlock();
            }
        }
        return actionResult(ret,model.getHeaderInfo().getId());
    }

    /**
     * @Des 新增单据时为每条零件生成行号
     * @Date 2021/4/21 16:31
     * @Author wangzhaoyu
     * @Param [model]
     * @Return void
     */
    void generalLineNo4SaleIntentionDetail(SaleAddVO model){
        if(model == null){
            return ;
        }
        List<SaleIntentionDetailVO> materialList = model.getMaterialList();
        int i = 0;
        for(SaleIntentionDetailVO saleIntentionDetailVO : materialList){
            i++;
            saleIntentionDetailVO.setLineNo(i);
        }
    }

    @RequestMapping(value = "/balance",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult balance(@RequestBody SaleAddVO model)throws Exception{
        if(model==null){
            return actionResult(ErrorCode.IllegalArument);
        }
        model.getHeaderInfo().setStatus(String.valueOf(SaleStatus.Submit.getCode()));
        model.getHeaderInfo().setCreatorId(getUserId());
        model.getHeaderInfo().setSupplierOrgId(getOrgId());
        model.getHeaderInfo().setCreateName(getUserName());
        try{
            String deliveryNo = saleIntentionService.balance(model);
            if(StringUtil.isNullOrEmpty(deliveryNo)){
                return actionResult(ErrorCode.Failure);
            }else{
                return actionValueResult(deliveryNo);
            }
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/updateDeliveryDate",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult updateDeliveryDate(@RequestBody SaleIntentionDetailVO intentionDetailVO)throws Exception{
        if(intentionDetailVO == null) {
            intentionDetailVO = new SaleIntentionDetailVO();
        }
        intentionDetailVO.setDeliveryCreateId(getUserId());
        intentionDetailVO.setDeliveryCreateName(getUserName());
        return actionResult(saleIntentionService.updateDeliveryDate(intentionDetailVO, getOrgId()));
    }

    @RequestMapping(value = "/updateLackRemark",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult updateLackRemark(@RequestBody SaleIntentionDetailVO intentionDetailVO)throws Exception{
        if(intentionDetailVO == null) {
            intentionDetailVO = new SaleIntentionDetailVO();
        }
        intentionDetailVO.setLackCreateId(getUserId());
        return actionResult(saleIntentionService.updateLackRemark(intentionDetailVO, getOrgId()));
    }

    @RequestMapping(value = "/item", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult item(String id) {
        if (StringUtils.isEmpty(id)) {
            return actionResult(ErrorCode.IllegalArument);
        }
        try {
            return actionValueResult(saleIntentionService.item(id, false));
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
    }

    @RequestMapping(value = "/itemSaleInfo",method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult itemSaleInfo(String id){
        if(StringUtils.isEmpty(id)){
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(ErrorCode.Success,saleIntentionService.itemSaleInfo(id));
    }

    @RequestMapping(value = "/itemByDeliveryNote",method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult itemByDeliveryNote(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(ErrorCode.Success,saleIntentionService.itemByDeliveryNote(id));
    }

    @RequestMapping(value = "/purchaseCreateQuerySaleIntention",method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult purchaseCreateQuerySaleIntention(String id) throws Exception {
        if(StringUtils.isEmpty(id)){
            return actionResult(ErrorCode.IllegalArument);
        }
        try{
            SaleAddVO saleAddVO = saleIntentionService.purchaseCreateQuerySaleIntention(id);
            return actionResult(ErrorCode.Success, saleAddVO);
        }catch (Exception e){
            return ActionResultUtil.errorActionResult(ErrorCode.Failure.getCode(),e.getMessage());
        }

    }

    @RequestMapping(value = "/findDeliveryNum",method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult findByDeliveryNum(@RequestParam("saleNo") String saleNo,
                                          @RequestParam("warehouseCode") String warehouseCode)throws Exception{
        if(StringUtils.isEmpty(saleNo) || StringUtils.isEmpty(warehouseCode)){
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(ErrorCode.Success,saleIntentionService.findDeliveryNum(saleNo, warehouseCode, getOrgId()));
    }

    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.SaleIntention.DEL)
    public ActionResult remove(@RequestBody DeleteReasonVO deleteReasonVO)throws Exception{
        if(deleteReasonVO==null||StringUtil.isNullOrEmpty(deleteReasonVO.getId())){
            return actionResult(ErrorCode.IllegalArument);
        }
        try {
            return actionResult(saleIntentionService.remove(deleteReasonVO.getId(),deleteReasonVO.getDeleteReason(),getOrgId(),getUserId(),getUserName()));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }


    @RequestMapping(value = "/export",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.SaleIntention.EXPORT)
    public void export(String[] ids)throws Exception {
        saleIntentionService.export(Arrays.asList(ids));
    }

    @RequestMapping(value = "/exportAll",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.SaleIntention.EXPORT)
    public void exportAll(SaleIntentionVO condition)throws Exception {
        condition.setSupplierOrgId(getOrgId());
        saleIntentionService.exportAll(condition);
    }


    @ResponseBody
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult importExcel(HttpServletRequest request) throws Exception{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile( multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        FunctionResult<String> result=new FunctionResult<>();
        if (!fileName.trim().endsWith(".xls")) {
            result.setCode(ErrorCode.ImportExcelEndWithXLS);
        } else {
            InputStream in = file.getInputStream();
            String dealerOrgId = request.getParameter("x-dealerOrgId");
            String targetOrgId = request.getParameter("x-targetOrgId");
            result= saleIntentionService.importExcel(in, dealerOrgId, getOrgId(), targetOrgId);
        }
        return actionResult(result.getCode(), result.getValue());
    }

    @ResponseBody
    @RequestMapping(value = "/importReplaceMaterial", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult importReplaceMaterial(HttpServletRequest request) throws Exception{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile( multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        FunctionResult<String> result=new FunctionResult<>();
        if (!fileName.trim().endsWith(".xls")) {
            result.setCode(ErrorCode.ImportExcelEndWithXLS);
        } else {
            String dealerOrgId = request.getParameter("x-dealerOrgId");
            String targetOrgId = request.getParameter("x-targetOrgId");
            String saleId = request.getParameter("x-saleId");
            if (StringUtils.isBlank(dealerOrgId)) {
                dealerOrgId = getOrgId();
            }
            InputStream in = file.getInputStream();
            result = saleIntentionService.importReplaceExcel(saleId, in, dealerOrgId, getOrgId(), targetOrgId);
        }
        return actionResult(result.getCode(), result.getValue());
    }

    @RequestMapping(value = "/download",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public void download() throws Exception {
        saleIntentionService.download();
    }

//    @RequestMapping(value = "/getSapPrice",method = RequestMethod.GET)
//    @FastMappingInfo(needLogin = true)
//    public ActionResult getSapPrice(String materialsNo) throws Exception{
//        BigDecimal price=saleIntentionService.getSapPrice(materialsNo,getOrgId());
//        if(price==null){
//            return actionResult(ErrorCode.IllegalArument);
//        }
//        return actionResult(price);
//    }

    /**
     * 外部接口
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addSaleOrder", method = RequestMethod.POST)
    public ActionResult addSaleOrder(@RequestBody SaleAddVO model) throws Exception {
        return doAddSaleOrder(model);
    }

    /**
     * 塔机备件销售外部接口
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/tjSaleIntention", method = RequestMethod.POST)
    public ActionResult tjSaleIntention(@RequestBody SaleAddVO model)throws Exception {
        LogHelper.monitor("塔机备件销售外部接口参数"+ JsonUtil.objectToString(model));
        //crmOrder重复单号校验
        ActionResult crmOrderDulpCheck = crmOrderDulpCheck(model);
        if(crmOrderDulpCheck != null && successActionResult(crmOrderDulpCheck)){
            return crmOrderDulpCheck;
        }
        //参数处理
        List<SaleIntentionDetailVO> materialList = model.getMaterialList();
        for(SaleIntentionDetailVO detailVO : materialList){
            detailVO.setPrice(detailVO.getUnitPrice());
            detailVO.setUnitPriceAfterAdjust(detailVO.getUnitPrice());
        }
        return tjSaleIntentionAddSaleOrder(model);
    }

    /**判断crmOrder是否已经存在记录，如果存在则返回操作成功，同时返回存在的PMS编号--
     这么返回的原因crm调接口大多加在签核流程里面，多次点击触发接口，返回已存在，会影响签核的动作（具体可以问瑞泰-黄远辉）
     返回null代表流程可以继续往下走，返回code=0表示已经存在数据，直接返回已存在的数据*/
    private ActionResult crmOrderDulpCheck(SaleAddVO model) {
        String crmOrder = model.getHeaderInfo().getCrmOrder();
        if(StringUtils.isEmpty(crmOrder)){
            return actionResult(ErrorCode.Failure,"crm订单号不能为空","crm订单号不能为空");
        }
        List<SaleIntentionDO> saleIntentions = saleIntentionService.getSaleIntentionByCrmOrder(crmOrder);
        if(!CollectionUtils.isEmpty(saleIntentions)){
            return actionResult(ErrorCode.Success,"CRM单号已存在",saleIntentions.get(0).getSaleNo());
        }
        return null;
    }

    /**
     * 外部接口。接口验证，后续对外提供调用请使用此接口
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addSaleOrderBySec", method = RequestMethod.POST)
    @ExternalApiRequest(ApiCheckOptionEnum.OPTION_SECRET)
    public ActionResult addSaleOrderBySec(@RequestBody SaleAddVO model) throws Exception {
        return doAddSaleOrder(model);
    }


    private ActionResult tjSaleIntentionAddSaleOrder(SaleAddVO model) {
        if (model == null || model.getHeaderInfo() == null || model.getMaterialList().isEmpty()) {
            return actionResult(ErrorCode.IllegalArument);
        }
        LogHelper.monitor("addSaleOrder接口入参：" + model.toString());
        model.getHeaderInfo().setStatus(String.valueOf(SaleStatus.Saved.getCode()));
        model.getHeaderInfo().setCreateType(1);//手动创建
        ActionResult ret;
        try {
            ret = saleIntentionService.addSaleOrder4Tj(model);
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        LogHelper.monitor("===addSaleOrder接口结束===");
        return ret;
    }


    private ActionResult doAddSaleOrder(SaleAddVO model) {
        if (model == null || model.getHeaderInfo() == null || model.getMaterialList().isEmpty()) {
            return actionResult(ErrorCode.IllegalArument);
        }
        LogHelper.monitor("addSaleOrder接口入参：" + model.toString());
        model.getHeaderInfo().setStatus(String.valueOf(SaleStatus.Saved.getCode()));
        model.getHeaderInfo().setCreateType(1);//手动创建
        ActionResult ret;
        try {
            ret = saleIntentionService.addSaleOrder(model);
        } catch (Exception e) {
            return actionResult(ErrorCode.Failure, e.getMessage());
        }
        LogHelper.monitor("===addSaleOrder接口结束===");
        return ret;
    }


    /**
     * 调整销售意向<br>
     *     调整销售意向的零件详细，调整数量不可大于已出库数量
     * @param saleAddVO
     * @return
     */
    @RequestMapping(value = "/adjust",method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult adjust(@RequestBody SaleAddVO saleAddVO) throws Exception
    {
        try {
            saleAddVO.getHeaderInfo().setCashShortAndOver(DecimalUtil.yuan2fenDefauleZero(saleAddVO.getHeaderInfo().getCashShortAndOver()));
            return actionResult(saleIntentionService.adjust(saleAddVO,getOrgId(),getUserId(),getUserName()));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }

    }

    @RequestMapping(value = "/listReceiverInfo", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true)
    public ActionResult listByReceiverName(String purchaseOrgId, String receiverName) throws Exception {
        return actionValueResult(saleIntentionService.listReceivers(purchaseOrgId, getOrgId(), receiverName));
    }

    @RequestMapping(value = "/synPrice", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.SaleIntention.SYN_PRICE)
    public ActionResult synPrice(@RequestBody SaleIntentionVO condition) throws Exception {
        if(condition == null || StringUtil.isNullOrEmpty(condition.getId())){
            return actionResult(ErrorCode.IllegalArument);
        }
        try {
            return actionResult(saleIntentionService.synPrice(condition.getId()));
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @RequestMapping(value = "/bathSynPrice", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.SaleIntention.SYN_PRICE)
    public ActionResult bathSynPrice(@RequestBody String[] ids) throws Exception{
        if(ids==null){
            return actionResult(ErrorCode.IllegalArument);
        }
        try{
            for (String id:ids
                 ) {
                ErrorCode code=saleIntentionService.synPrice(id);
                if(code!=ErrorCode.Success){
                    return actionResult(code);
                }
            }
            return actionResult(ErrorCode.Success);
        }catch (Exception e){
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping(value = "/importAttach", method = RequestMethod.POST)
    @FastMappingInfo(needLogin = true,code = AuthCode.SaleIntention.UPLOAD_FILE)
    public ActionResult importAttach(HttpServletRequest request) throws Exception{
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile( multipartRequest.getFileNames().next());
        String billId = request.getParameter("x-billId");
        return actionResult(saleIntentionService.importAttach(billId, file));
    }

    @RequestMapping(value = "/downloadAttach",method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public void downloadAttach(String billId) throws Exception {
        saleIntentionService.downloadAttach(billId);
    }

    @ResponseBody
    @RequestMapping(value = "/getDetailQty", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult getDetailQty(String saleIntentionId) {
       return actionValueResult(saleIntentionService.getDetailQty(saleIntentionId));
    }

    @RequestMapping(value = "/updateAfterSaleStatus", method = RequestMethod.GET)
    @ExternalApiRequest(ApiCheckOptionEnum.OPTION_SECRET)
    public ActionResult updateAfterSaleStatus(Integer afterSaleStatus, String saleNo, String sapCode) {
        try {
            saleIntentionService.updateAfterSaleStatus(afterSaleStatus, saleNo, sapCode);
        } catch (Exception e) {
            return new ActionResult(yb.ecp.fast.infra.constants.ErrorCode.Failure.getCode(), e.getMessage());
        }
        return actionResult(ErrorCode.Success);
    }

    @RequestMapping(value = "/audit4JC", method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult audit4JC(String id, Integer checkFlag) {
        try {
            saleIntentionService.audit4JC(id, checkFlag, getUserId());
        } catch (Exception e) {
            return new ActionResult(ErrorCode.Failure.getCode(), e.getMessage());
        }
        return actionResult(ErrorCode.Success);
    }

    @ResponseBody
    @RequestMapping(value = "/importLackInfo", method = RequestMethod.POST)
    @ApiOperation("导入缺货报表信息")
    @FastMappingInfo(needLogin = true)
    public ActionResult importLackInfo(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile(multipartRequest.getFileNames().next());
        String fileName = file.getOriginalFilename();
        FunctionResult<String> result = new FunctionResult<>();
        try {
            if (!fileName.trim().endsWith(".xls") && !fileName.trim().endsWith(".xlsx")) {
                throw new Exception("文件格式错误");
            } else {
                InputStream in = file.getInputStream();
                result = saleIntentionService.importLackInfo(in, getOrgId(), getUserId());
            }
        } catch (Exception e) {
            return actionResult(ErrorCode.IllegalArument, e.getMessage());
        }
        return actionResult(result.getCode(), result.getValue());
    }

    @RequestMapping(value = "/downloadLackTemplate",method = RequestMethod.POST)
    @ApiOperation("下载缺货报表导入模板")
    @FastMappingInfo(needLogin = true)
    public void downloadLackTemplate() throws Exception {
        saleIntentionService.downloadLackTemplate();
    }

    @Autowired
    private DeliveryNoteService deliveryNoteService;

    /**
     * 塔机外部接口--同步前移备件当做备件销售处理
     * @param model
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addSaleOrder4Tj", method = RequestMethod.POST)
//    @ExternalApiRequest
    public ActionResult addSaleOrder4Tj(@RequestBody SaleAddVO model) throws Exception {
        //
        ActionResult actionResult = addSaleOrder4TjParamPreHandle(model);
        if(!successActionResult(actionResult)){
            return actionResult;
        }
        ActionResult result = doAddSaleOrder(model);
//        try {
//            String saleNo = (String)result.getValue();
//            SaleAddVO saleAddVO = saleIntentionService.selectByNo(saleNo);
//            SaleIntentionVO saleIntentionVO = saleAddVO.getHeaderInfo();
//            List<SaleIntentionDetailVO>  detailVOS = saleAddVO.getMaterialList();
//
//            DeliveryNoteAddVO deliveryNoteAddVO = new DeliveryNoteAddVO();
//            DeliveryNoteVO deliveryNoteVO = new DeliveryNoteVO();
//            List<DeliveryNoteDetailVO> noteDetailVOS = new ArrayList<>();
//
//            BeanUtils.copyProperties(saleIntentionVO, deliveryNoteVO);
//            deliveryNoteVO.setId(null);
//            deliveryNoteVO.setSaleNo(saleNo);
//            deliveryNoteVO.setAddress(saleIntentionVO.getReceiveAddress());
//
//            DeliveryNoteDetailVO noteDetailVO;
//            for (SaleIntentionDetailVO saleIntentionDetailVO : detailVOS) {
//                noteDetailVO = new DeliveryNoteDetailVO();
//                BeanUtils.copyProperties(saleIntentionDetailVO, noteDetailVO);
//                noteDetailVOS.add(noteDetailVO);
//            }
//            deliveryNoteAddVO.setHeaderInfo(deliveryNoteVO);
//            deliveryNoteAddVO.setMaterialList(noteDetailVOS);
//            deliveryNoteService.add(deliveryNoteAddVO, saleIntentionVO.getCreatorId(), saleIntentionVO.getSupplierOrgId());
//        } catch (Exception e) {
//            LogHelper.error("塔机销售意向创建发货通知单失败：" + e.getMessage(),ErrorCode.Failure.getCode());
//            System.out.println("失败：" + e.getMessage());
//        }
        return result;
    }

    /**
     * 同步前移备件当做备件销售处理参数预处理
     * */
    private ActionResult addSaleOrder4TjParamPreHandle(SaleAddVO model) throws Exception {

        //处理塔机传过来的参数
        List<SaleIntentionDetailVO> materialList = model.getMaterialList();
        if(materialList == null){
            return actionResult(ErrorCode.Failure, "参数错误","参数错误");
        }
        for(SaleIntentionDetailVO detail : materialList){
            BigDecimal unitPrice = detail.getUnitPrice();
            if(unitPrice == null){
                return actionResult(ErrorCode.Failure, "缺少零件单价参数","缺少零件单价参数");
            }
            detail.setUnitPriceAfterAdjust(unitPrice);
            detail.setPrice(unitPrice);
            BigDecimal qty = detail.getQty();
            if(qty == null || qty.compareTo(BigDecimal.ZERO) <= 0){
                return actionResult(ErrorCode.Failure, "零件数量参数错误","零件数量参数错误");
            }
            detail.setAmountAfterAdjust(qty);

            //拼接每个零件的单位unit 和 零件名称
            String materialNo = detail.getMaterialsNo();
            PriMaterialsDO materialsInfo = externalParamCheckService.getMaterialsInfo(materialNo);
            if(materialsInfo != null){
                String unit = materialsInfo.getUnit();
                detail.setUnit(unit);
                String materialsDes = materialsInfo.getMaterialsDes();
                if(!StringUtils.isEmpty(materialsDes)){
                    detail.setMaterialsDes(materialsDes);
                }
            }
        }
        //根据销售仓库名称匹配销售仓库编码
        String outWarehouseDesc = model.getHeaderInfo().getOutWarehouseDesc();
        String orgId = externalParamCheckService.getOrgIdBySapCode("2130");
        List<WarehouseDO> outWareHouses = regionAllotService.getWareHousesByOrgAndDescription(orgId, outWarehouseDesc);
        if(CollectionUtils.isEmpty(outWareHouses)){
            return actionResult(ErrorCode.Failure, "销售仓库:"+outWarehouseDesc+"无法匹配到销售仓库","销售仓库:"+outWarehouseDesc+"无法匹配到销售仓库");
        }
        WarehouseDO warehouseDO = outWareHouses.get(0);
        model.getHeaderInfo().setOutWarehouse(warehouseDO.getWarehouseCode());
        return actionResult(ErrorCode.Success);
    }

    @RequestMapping(value = "/item4JckDelivery",method = RequestMethod.GET)
    @FastMappingInfo(needLogin = true)
    public ActionResult item4JckDelivery(String id){
        if(StringUtils.isEmpty(id)){
            return actionResult(ErrorCode.IllegalArument);
        }
        return actionResult(ErrorCode.Success,saleIntentionService.item4JckDelivery(id));
    }

//    @RequestMapping(value = "/syncSaleIntention4NS",method = RequestMethod.GET)
//    @FastMappingInfo(needLogin = true)
//    public ActionResult syncSaleIntention4NS(String id) throws Exception{
//        if(StringUtils.isEmpty(id)){
//            return actionResult(ErrorCode.IllegalArument);
//        }
//
//        return actionResult(saleIntentionService.synSaleIntention4NS(id));
//    }

}
